package com.zh.springcloud.controller;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.zh.springcloud.feign.OrderFeign;
import com.zh.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


/**
 * @Description:
 * @ClassName PaymentController
 * @date: 2021.06.08 15:50
 * @Author: zhanghang
 */
@RestController
@Slf4j
public class PaymentController {

	@Autowired
	private PaymentService paymentService;

	@Autowired
	private OrderFeign orderFeign;

	@Value("${server.port}")
	private String serverPort;

	@GetMapping("/payment/test")
	public String test(){
		return orderFeign.test();
	}

	@GetMapping("/payment/hystrix/ok/{id}")
	public String paymentinfo_ok(@PathVariable("id") Integer id){
		String result = paymentService.paymentInfo_ok(id);
		log.info("====result ->"+result);
		return result;
	}

	@GetMapping("/payment/hystrix/circuitBreaker/{id}")
	@HystrixCommand(fallbackMethod = "circuitBreaker_fallback", commandProperties = {
			@HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 是否开启断路器
			@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
			@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期
			@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60") // 失败率达到多少后跳闸，这里是60%
	})
	public String circuitBreaker(@PathVariable("id") Integer id){
		if (id  < 0 ){
			throw new RuntimeException("不能小于零");
		}
		String str = IdUtil.simpleUUID();
		return Thread.currentThread().getName() + " \t "+ "调用成功，流水号："+str;
	}

	public String circuitBreaker_fallback(@PathVariable("id") Integer id){
		return "id 不能为负数，请稍后再试，id:"+id;
	}

	@GetMapping("/payment/hystrix/timeout/{id}")
	@HystrixCommand(fallbackMethod = "paymentinfo_timeoutHandler", commandProperties =
		@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
	)
	public String paymentinfo_timeout(@PathVariable("id") Integer id){
		String result = paymentService.paymentInfo_timeout(id);
		log.info("====result ->"+result);
		return result;
	}

	public String paymentinfo_timeoutHandler(@PathVariable("id") Integer id){
		return "线程："+Thread.currentThread().getName()+" paymentInfo_timeoutHandler,id:"+id+" \t "+"/(ㄒoㄒ)/~~";

	}
}
